/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 * 输入：head = [1,2,3,3,4,4,5]
输出：[1,2,5]
 */
const createListNode = arr => {
  function ListNode(val, next) {
    this.val = val === undefined ? 0 : val
    this.next = next === undefined ? null : next
  }
  let oldListNode = null
  for (let index = arr.length - 1; index > -1; index--) {
    const val = arr[index]
    const newListNode = new ListNode(val, oldListNode)
    oldListNode = newListNode
  }
  return oldListNode
}
var deleteDuplicates = function (head) {
  if (!head || !head.next) {
    return head
  }
  let newhead = head
  let last = null
  let newlast = null
  let lastNode = null
  let returnhead = true
  while (newhead.next) {
    let i = 0
    while (newhead.next && newhead.val === newhead.next.val) {
      lastNode = newhead
      newhead = newhead.next
      i++
    }
    if (last) {
      if (i === 0) {
        // last.next = newhead
        newlast.next = newhead
        newlast = newlast.next
      }
    } else {
      if (i === 0) {
        last = newhead
        newlast = last
      } else {
        returnhead = false
      }
    }
    lastNode = newhead
    newhead.next && (newhead = newhead.next)
    // if (newhead.val === newhead.next.val) {
    //   if (newhead.next.next) {
    //     newhead.next = newhead.next.next
    //   } else {
    //     newhead.next = null
    //   }
    // } else {
    //   newhead = newhead.next
    // }
  }
  if (newhead.val !== lastNode.val) {
    if (last) {
      newlast.next = lastNode.next
    } else {
      head = lastNode.next
      last = lastNode.next
    }
  } else {
    newlast && (newlast.next = null)
  }

  return returnhead ? head : last
}
console.log(deleteDuplicates(createListNode([0, 1, 2, 2, 3, 4])))
